import os
from typing import Optional
from pydantic import field_validator
from pydantic_settings import BaseSettings, SettingsConfigDict


class Settings(BaseSettings):
    """应用配置类"""

    # 应用基础配置
    APP_NAME: str = "ewentianshi"
    APP_VERSION: str = "1.0.0"
    APP_DESCRIPTION: str = "AI 脱发检测"
    DEBUG_MODE: bool = True
    APP_HOST: str = "127.0.0.1"
    APP_PORT: int = 8088

    # 静态文件配置
    STATIC_DIR: str = "static"
    STATIC_URL: str = "/static"
    STATIC_NAME: str = "static"

    # 安全配置
    SECRET_KEY: str = "please-set-secret-key-in-env-file"  # 应从环境变量读取
    ALGORITHM: str = "HS256"
    ACCESS_TOKEN_EXPIRE_MINUTES: int = 10080  # 7天（一周）
    ENABLE_JWT_AUTH: bool = True  # 是否启用JWT鉴权中间件

    # MySQL数据库配置
    MYSQL_HOST: str = "localhost"
    MYSQL_PORT: int = 3306
    MYSQL_USER: str = "root"
    MYSQL_PASS: str = "123456"
    MYSQL_DB: str = "ewentianshi_dev"

    # Redis配置
    REDIS_HOST: str = "localhost"
    REDIS_PORT: int = 6379
    REDIS_DB: int = 0
    REDIS_PASSWORD: Optional[str] = None
    REDIS_MAX_CONNECTIONS: int = 10

    # 日志配置
    LOG_LEVEL: str = "INFO"
    LOG_FILE: str = "logs/app.log"
    LOG_FORMAT: str = "%(asctime)s - %(name)s - %(levelname)s - %(message)s"

    # CORS配置
    CORS_ORIGINS: list = ["*"]
    CORS_METHODS: list = ["*"]
    CORS_HEADERS: list = ["*"]

    # 限流配置
    RATE_LIMIT_REQUESTS: int = 100
    RATE_LIMIT_WINDOW: int = 60

    # 阿里云OSS配置
    OSS_ACCESS_KEY_ID: str = "your-access-key-id"
    OSS_ACCESS_KEY_SECRET: str = "your-access-key-secret"
    OSS_ENDPOINT: str = "oss-cn-shanghai.aliyuncs.com"
    OSS_BUCKET_NAME: str = "yuanzhifa"
    OSS_STORAGE_PATH: str = "ewentianshi/hair/"
    OSS_AVATAR_PATH: str = "ewentianshi/avatar/"
    OSS_HAIR_PATH: str = "ewentianshi/hair/"
    
    # 默认头像配置
    DEFAULT_AVATAR_URL: str = "https://yuanzhifa.oss-cn-shanghai.aliyuncs.com/ewentianshi/static/%E9%BB%98%E8%AE%A4%E5%A4%B4%E5%83%8F.png"

    # AI配置
    AI_API_URL: str = "https://api.siliconflow.cn"
    AI_API_KEY: str = "your-ai-api-key"
    AI_MODEL: str = "Qwen/Qwen2.5-VL-72B-Instruct"
    AI_API_TIMEOUT: int = 30
    AI_CONFIDENCE_THRESHOLD: float = 0.3
    
    # 打卡配置
    CHECKIN_BASE_POINTS: int = 10  # 基础打卡积分
    CHECKIN_BONUS_MAX: int = 20    # 连续打卡最大奖励积分
    CHECKIN_RESET_HOUR: int = 0    # 打卡重置时间（小时）
    CHECKIN_RESET_MINUTE: int = 1  # 打卡重置时间（分钟）

    @field_validator("CORS_ORIGINS", mode="before")
    @classmethod
    def parse_cors_origins(cls, v):
        if isinstance(v, str):
            return [v] if v != "*" else ["*"]
        return v

        model_config = SettingsConfigDict(env_file_encoding="utf-8", extra="ignore")


def _get_env_file() -> str:
    """获取环境文件名"""
    env = os.getenv("ENV", "develop")
    return ".env.develop" if env == "develop" else ".env.product"


_config_cache = {}


def get_settings() -> Settings:
    """获取配置实例，支持动态环境变量"""
    env = os.getenv("ENV", "develop")

    if env not in _config_cache:
        # 创建Settings实例时指定环境文件
        env_file = _get_env_file()

        # 使用临时的SettingsConfigDict来指定env_file
        class DynamicSettings(Settings):
            model_config = SettingsConfigDict(
                env_file=env_file, env_file_encoding="utf-8", extra="ignore"
            )

        _config_cache[env] = DynamicSettings()

    return _config_cache[env]


def get_config_info() -> dict:
    """获取配置信息用于启动时显示"""
    settings = get_settings()
    return {
        "应用名称": settings.APP_NAME,
        "应用版本": settings.APP_VERSION,
        "调试模式": settings.DEBUG_MODE,
        "服务地址": f"{settings.APP_HOST}:{settings.APP_PORT}",
        "MySQL数据库": f"{settings.MYSQL_HOST}:{settings.MYSQL_PORT}/{settings.MYSQL_DB}",
        "MySQL用户": settings.MYSQL_USER,
        "Redis服务器": f"{settings.REDIS_HOST}:{settings.REDIS_PORT}/{settings.REDIS_DB}",
        "Redis连接池": f"{settings.REDIS_MAX_CONNECTIONS}个连接",
        "日志级别": settings.LOG_LEVEL,
        "日志文件": settings.LOG_FILE,
        "CORS源": settings.CORS_ORIGINS,
        "限流设置": f"{settings.RATE_LIMIT_REQUESTS}次/{settings.RATE_LIMIT_WINDOW}秒",
        "环境文件": _get_env_file(),
    }


# Tortoise ORM 配置
def get_tortoise_config():
    """获取Tortoise ORM配置"""
    settings = get_settings()
    return {
        "connections": {
            "default": {
                "engine": "tortoise.backends.mysql",
                "credentials": {
                    "host": settings.MYSQL_HOST,
                    "port": settings.MYSQL_PORT,
                    "user": settings.MYSQL_USER,
                    "password": settings.MYSQL_PASS,
                    "database": settings.MYSQL_DB,
                    "charset": "utf8mb4",
                },
            },
        },
        "apps": {
            "models": {
                "models": ["src.models", "aerich.models"],
                "default_connection": "default",
            }
        },
    }


TORTOISE_ORM = get_tortoise_config()